package org.springblade.auth.converter;

import org.springblade.core.launch.constant.TokenConstant;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.core.tool.utils.Func;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class CsjJwtAccessTokenConverter extends JwtAccessTokenConverter {
	@Override
	protected String encode(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
		Map<String,Object> map = new HashMap<>(accessToken.getAdditionalInformation());
		map.put(TokenConstant.TOKEN_TYPE, TokenConstant.ACCESS_TOKEN);
		Map<String,String> finalMap = map.keySet().stream().collect(Collectors.toMap((one)->one ,(one)-> Func.toStr(map.get(one))));
		return SecureUtil.createJWT(finalMap, "audience", "issuser", TokenConstant.ACCESS_TOKEN).getToken();
	}

	@Override
	protected Map<String, Object> decode(String token) {
		Map<String, Object> map = SecureUtil.parseJWT(token);
		map.put("exp", Func.toLong(map.get("exp")));
		map.put("nbf", Func.toLong(map.get("nbf")));
		return map;
	}
}
